//
//  HYFileManager.m
//  XPlayer
//
//  Created by liguoqing on 2023/8/9.
//

#import "HYFileManager.h"

// 视频封面下载文件夹
NSString *const VideoCoverImageName = @"VideoImage";
// 视频下载
NSString *const VideoDownloadName = @"VideoDownload";
// 视频临时下载目录
NSString *const VideoTempDownloadName = @"VideoTempDownload";
// 相册视频文件夹
NSString *const PhotoVideoName = @"PhotoVideo";
// 文件传输文件夹
NSString *const WIFIFolderName = @"WIFI";
// 视频下载文件夹名
NSString *const VideoFileDownloadDirectoryName = @"VideoFile";

@interface HYFileManager ()

@property (nonatomic, strong) NSArray *docTypes;

@property (nonatomic, strong) NSArray *picTypes;

@property (nonatomic, strong) NSArray *audioTypes;

@property (nonatomic, strong) NSArray *videoTypes;

@property (nonatomic, strong) NSArray *zipTypes;

@end

@implementation HYFileManager


+ (instancetype)shareManager
{
    static HYFileManager *fileManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        fileManager = [[self alloc]init];
    });
    return fileManager;
}

// 视频封面保存路径
+ (NSString *)videoImageSavePathWithFileName:(NSString *)fileName
{
    BOOL isDir = NO;
    NSString *rootPath = [self videoCoverImageDownloadRootPath];
    BOOL existed = [[NSFileManager defaultManager] fileExistsAtPath:rootPath isDirectory:&isDir];
    if(!isDir && !existed){
        [[NSFileManager defaultManager] createDirectoryAtPath:rootPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return [rootPath stringByAppendingPathComponent:fileName];
}

// 视频封面
+ (NSString *)videoCoverImageDownloadRootPath
{
    return [[self videoFileDownloadRootPath] stringByAppendingPathComponent:VideoCoverImageName];
}

// wifi导入路径
+ (NSString *)wifiImportFileDocumentPath
{
    return [self documentDirectory];
}

+ (NSString *)wifiImportFileDocumentPathWithFolerName:(NSString *)folerName
{
    if([folerName isEqualToString:HomeFolder]){
        return [self documentDirectory];
    }
    BOOL isDir = NO;
    NSString *rootPath = [self wifiImportFolderRootPath];
    BOOL existed = [[NSFileManager defaultManager] fileExistsAtPath:rootPath isDirectory:&isDir];
    if(!existed){
        [[NSFileManager defaultManager] createDirectoryAtPath:rootPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *folderPath = [rootPath stringByAppendingPathComponent:folerName];
    BOOL isExisted = [[NSFileManager defaultManager] fileExistsAtPath:folderPath isDirectory:&isDir];
    if(isExisted){
        [[NSFileManager defaultManager] createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return folderPath;
}

// 根据相册导入的视频名称获取根路径
+ (NSString *)fetchPhotoVideoImportPathWithVideoName:(NSString *)videoName
{
    BOOL isDir = NO;
    NSString *rootPath = [self photoVideoImportFolderRootPath];
    BOOL existed = [[NSFileManager defaultManager] fileExistsAtPath:rootPath isDirectory:&isDir];
    if(!isDir && !existed){
        [[NSFileManager defaultManager] createDirectoryAtPath:rootPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return [rootPath stringByAppendingPathComponent:videoName];
}

// wifi导入根文件目录
+ (NSString *)wifiImportFolderRootPath
{
    return [[self libraryDirectory] stringByAppendingPathComponent:WIFIFolderName];
}
// 相册视频跟路径
+ (NSString *)photoVideoImportFolderRootPath
{
    return [[self libraryDirectory] stringByAppendingPathComponent:PhotoVideoName];
}

/// 创建文件路径
+ (NSString *)createFolderPathWithFolderName:(NSString *)folderName
{
    BOOL isDir = NO;
    NSString *folderPath = [[self documentDirectory] stringByAppendingPathComponent:folderName];
    BOOL existed = [[NSFileManager defaultManager] fileExistsAtPath:folderPath isDirectory:&isDir];
    if(!isDir && !existed){
        [[NSFileManager defaultManager] createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
    }else{
        // 返回空说明文件已存在，不用重复创建
        return @"";
    }
    return folderPath;
}

+ (NSString *)createFolderPathWithFolderName:(NSString *)folderName filePath:(NSString *)filePath
{
    BOOL isDir = NO;
    NSString *folderPath = [filePath stringByAppendingPathComponent:folderName];
    BOOL existed = [[NSFileManager defaultManager] fileExistsAtPath:folderPath isDirectory:&isDir];
    if(!isDir && !existed){
        [[NSFileManager defaultManager] createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
    }else{
        // 返回空说明文件已存在，不用重复创建
        return @"";
    }
    return folderPath;
}

/// 获取文件夹路径
+ (NSString *)fetchFolderPathWithFolderName:(NSString *)folderName
{
    return [[self documentDirectory] stringByAppendingPathComponent:folderName];
}

/// 移除文件夹路径
+ (BOOL)removeFolderPathWithFolderName:(NSString *)folderName
{
    NSString *folderPath = [self fetchFolderPathWithFolderName:folderName];
    return [[NSFileManager defaultManager] removeItemAtPath:folderPath error:nil];
}

/// 修改旧文件夹路径
+ (NSString *)moveFolderPathOldFolderPath:(NSString *)oldFolderPath newFolderName:(NSString *)newFolderName
{
    NSString *lastPathComponent = [oldFolderPath lastPathComponent];
    NSString *newFolderPath = [oldFolderPath stringByReplacingOccurrencesOfString:lastPathComponent withString:newFolderName];
    BOOL isSuccess = [[NSFileManager defaultManager] moveItemAtPath:oldFolderPath toPath:newFolderPath error:nil];
    if(isSuccess){
        return newFolderPath;
    }
    return @"";
}

+ (BOOL )moveFileWithFromPath:(NSString *)fromPath toPath:(NSString *)toPath
{
    NSString *lastPathComponent = [fromPath lastPathComponent];
    NSString *newPath = [toPath stringByAppendingPathComponent:lastPathComponent];
    return [[NSFileManager defaultManager] moveItemAtPath:fromPath toPath:newPath error:nil];
}

#pragma mark -获取下载路径
// 默认下载路径
+ (NSString *)videoDownloadPathWithFileName:(NSString *)fileName
{
    return [[self downloadRootPath] stringByAppendingPathComponent:fileName];
}
// 下载根路径
+ (NSString *)downloadRootPath
{
    return [[self videoFileDownloadRootPath] stringByAppendingPathComponent:VideoDownloadName];
}

// 默认下载临时文件路径
+ (NSString *)tempSavePathWithFileName:(NSString *)fileName
{
    return [[self tempDownloadRootPath] stringByAppendingPathComponent:fileName];
}
// 下载根路径
+ (NSString *)tempDownloadRootPath
{
    return [[self videoFileDownloadRootPath] stringByAppendingPathComponent:VideoTempDownloadName];
}

// 视频下载根路径
+ (NSString *)videoFileDownloadRootPath
{
    return [[self libraryDirectory] stringByAppendingPathComponent:VideoFileDownloadDirectoryName];
}

// document路径
+ (NSString *)documentDirectory
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDir = [paths objectAtIndex:0];
    NSFileManager *fileManager = [NSFileManager new];
    [fileManager setAttributes:[NSDictionary dictionaryWithObject:NSFileProtectionNone forKey:NSFileProtectionKey] ofItemAtPath:documentDir error:NULL];
    return documentDir;
}

// library路径
+ (NSString *)libraryDirectory
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *libraryDir = [paths objectAtIndex:0];
    NSFileManager *fileManager = [NSFileManager new];
    [fileManager setAttributes:[NSDictionary dictionaryWithObject:NSFileProtectionNone forKey:NSFileProtectionKey] ofItemAtPath:libraryDir error:NULL];
    return libraryDir;
}


+ (BOOL)checkValidVideoPlayUrl:(NSString *)videoUrl
{
    //WMV,AVI,MKV,RMVB,RM,XVID,MP4,3GP,MPG,MOV,m4v,m3u8
    if([videoUrl containsString:@".wmv"] || [videoUrl containsString:@".avi"] || [videoUrl containsString:@".mkv"] || [videoUrl containsString:@".rmvb"] || [videoUrl containsString:@".rm"] || [videoUrl containsString:@".xvid"] || [videoUrl containsString:@".mp4"] || [videoUrl containsString:@".3gp"] || [videoUrl containsString:@".mpg"] || [videoUrl containsString:@".mov"] || [videoUrl containsString:@".m4v"]||[videoUrl containsString:@".m3u8"]){
        return YES;
    }
    return NO;
}

+ (BOOL)checkValidAudioPlayUrl:(NSString *)audioUrl
{
    if([audioUrl containsString:@".mp3"] || [audioUrl containsString:@".wma"] || [audioUrl containsString:@".rm"] || [audioUrl containsString:@".acc"] || [audioUrl containsString:@".ogg"] || [audioUrl containsString:@".ape"] || [audioUrl containsString:@".flac"] || [audioUrl containsString:@".flv"]){
        return YES;
    }
    return NO;
}

/// 文件夹标识位
+ (NSString*)folderIdentification
{
    char data[10];
    for (int x=0;x<10;data[x++] = (char)('A' + (arc4random_uniform(26))));
    NSDate *  datenow= [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    NSString * n_str = [NSString stringWithFormat:@"%@%@",
                        [[NSString alloc] initWithBytes:data length:10 encoding:NSUTF8StringEncoding]
                        ,timeSp
                        ];
    
    return n_str;
}

+ (NSInteger)getCacheSizeWithFolderPath:(NSString *)folderPath
{
    NSArray *subpathArray= [kFileManager subpathsAtPath:folderPath];
    NSString *filePath = nil;
    NSInteger totleSize= [self getSingleFileSizeWithFilePath:folderPath];
    for (NSString *subpath in subpathArray){
        //拼接每一个文件的全路径
        filePath = [folderPath stringByAppendingPathComponent:subpath];
        //isDirectory，是否是文件夹，默认不是
        BOOL isDirectory = NO;
        //isExist，判断文件是否存在
        BOOL isExist = [kFileManager fileExistsAtPath:folderPath isDirectory:&isDirectory];
        if (isExist && isDirectory && ![filePath containsString:@".DS"]){
            totleSize += [self getCacheSizeWithFolderPath:filePath];
        }else{
            totleSize += [self getSingleFileSizeWithFilePath:filePath];
        };
    }
    return totleSize;
}

+ (NSInteger)getSingleFileSizeWithFilePath:(NSString *)filePath
{
    NSInteger fileLength = 0;
    if ([kFileManager fileExistsAtPath:filePath]) {
        NSError *error = nil;
        // 获取文件属性
        NSDictionary *fileDict = [kFileManager attributesOfItemAtPath:filePath error:&error];
        if (!error && fileDict) {
            fileLength = [fileDict fileSize];
        }
    }
    return fileLength;
}

+ (NSDate *)getSingalFileCreateDateWithFilePath:(NSString *)filePath
{
    if ([kFileManager fileExistsAtPath:filePath]) {
        NSError *error = nil;
        // 获取文件属性
        NSDictionary *fileDict = [kFileManager attributesOfItemAtPath:filePath error:&error];
        if (!error && fileDict) {
            return [fileDict fileCreationDate];
        }
    }
    return nil;
}

- (NSArray *)fetchImportfileTypes
{
    NSMutableArray *mutable = [NSMutableArray array];
    [mutable addObjectsFromArray:self.docTypes];
    [mutable addObjectsFromArray:self.picTypes];
    [mutable addObjectsFromArray:self.audioTypes];
    [mutable addObjectsFromArray:self.videoTypes];
    [mutable addObjectsFromArray:self.zipTypes];
    return [mutable copy];
}

// 获取文件类型
- (HYHomeFileType)fetchFileTypeWithFileName:(NSString *)fileName
{
    NSString *fileSuffix = [fileName componentsSeparatedByString:@"."].lastObject;
    if(fileSuffix){
        NSString *lower = [fileSuffix lowercaseString];
        if([self.docTypes containsObject:lower]){
            return HYHomeFileType_File;
        }else if ([self.picTypes containsObject:lower]){
            return HYHomeFileType_Pic;
        }else if ([self.audioTypes containsObject:lower]){
            return HYHomeFileType_Audio;
        }else if ([self.videoTypes containsObject:lower]){
            return HYHomeFileType_Video;
        }else if ([self.zipTypes containsObject:lower]){
            return HYHomeFileType_Zip;
        }
    }
    return HYHomeFileType_Other;
}

#pragma mark - loadLoazy
- (NSArray *)docTypes
{
    if(!_docTypes){
        _docTypes = @[@"doc",@"docx",@"xls",@"xlsx",@"txt",@"pdf",@"ppt",@"pptx",@"html",@"htm",@"key",@"rtf",@"epub"];
    }
    return _docTypes;
}
// bmp，jpg，png，tif，gif，pcx，tga，exif，fpx，svg，psd，cdr，pcd，dxf，ufo，eps，ai，raw，WMF，webp，avif，apng
- (NSArray *)picTypes
{
    if(!_picTypes){
        _picTypes = @[@"bmp",@"png",@"apng",@"jpg",@"jpeg",@"gif",@"avif",@"ico",@"tif",@"pcx",@"cdr",@"raw",@"fpx",@"ai",@"psd",@"webp"];
    }
    return _picTypes;
}

- (NSArray *)audioTypes
{
    if(!_audioTypes){
        _audioTypes = @[@"mp3",@"wma",@"rm",@"acc",@"ogg",@"ape",@"flac",@"flv"];
    }
    return _audioTypes;
}

- (NSArray *)videoTypes
{
    if(!_videoTypes){
        _videoTypes = @[@"wmv",@"avi",@"rmvb",@"rm",@"xvid",@"3gp",@"mov",@"m4v",@"mp4",@"m3u8"];
    }
    return _videoTypes;
}

- (NSArray *)zipTypes
{
    if(!_zipTypes){
        _zipTypes = @[@"zip",@"rar"];
    }
    return _zipTypes;
}

@end
